﻿using IdentityModel.Client;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Protocols.OpenIdConnect;

namespace WebAppCodeClient.Controllers
{
    [Authorize]
    public class HomeController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 获取API资源。
        /// </summary>
        /// <returns></returns>
        public async Task<IActionResult> ApiData()
        {
            //获取accessToken
            var accessToken = await HttpContext.GetTokenAsync(OpenIdConnectParameterNames.AccessToken);
            //请求API资源
            var httpClient = new HttpClient();
            //将获取到的AccessToken以Bearer的方案设置在请求头中
            httpClient.SetBearerToken(accessToken);
            //向API资源服务器请求受保护的API //http://localhost:5002/api/User/UserInfo
            var data = await httpClient.GetAsync("https://localhost:5001/api/customer/getlist");
            if (data.IsSuccessStatusCode)
            {
                var r = await data.Content.ReadAsStringAsync();
                ViewBag.ApiData = r;
            }
            else
            {
                ViewBag.ApiData = "获取API数据失败。";
            }
            return View();
        }


        public async Task<IActionResult> UserInfo()
        {
            return View();
        }

        public IActionResult Logout()
        {
            return SignOut("Cookies", "oidc");
        }
    }
}
